package servlets;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import beans.User;
import dao.UserDao;

/**
 * 本Servlet用于处理更新用户信息。
 * 提示：使用Part接口处理上传附件时必须设置@MultipartConfig注解，在@MultipartConfig可设定一个保存上传附件的保存目录，也可自行设定。
 */
@MultipartConfig
@WebServlet(urlPatterns = "/updateUser.do",initParams = {@WebInitParam(name="savePhotoDir",value="/WEB-INF/headPhoto/")})
public class UserUpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	//照片保存目录
    private String saveRealPath;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserUpdateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init(ServletConfig config) throws ServletException {
    	//获取照片初始化的照片保存目录
    	String savePhotoDir = config.getInitParameter("savePhotoDir");
    	saveRealPath = config.getServletContext().getRealPath(savePhotoDir);
    }
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		//获取待更新用户的id
		int uid = Integer.parseInt(request.getParameter("id"));
		//判断用户是否登录，如果未登录则不能更新，跳回到登录页面。
		User user = (User)request.getSession().getAttribute("loginUser");
		if (user == null) {
			out.println("你未登录！");
			response.setHeader("Refresh", "2;login.html");
		}else{
			//获取用户新的用户信息数据
			String realName = request.getParameter("realName");
			String email = request.getParameter("email");
			String cellphone = request.getParameter("cellphone");
			String address = request.getParameter("address");
			Part headPhoto = request.getPart("headPhoto");
			//创建一个用于更新的User对象，这是UserDao中update方法的参数就是一个User对象。
			//update方法中更新了除id和userName以外的所有数据，所以所有不能为null的字段都要有不为null的数据。
			User updateUser = new User();
			updateUser.setId(uid);
			updateUser.setUserName(user.getUserName());
			updateUser.setPwd(user.getPwd());
			updateUser.setRealName(realName);
			updateUser.setEmail(email);
			updateUser.setCellphone(cellphone);
			updateUser.setAddress(address);
			//如果有上传头像，先保存头像。
			if (headPhoto.getSize() > 0) {
				updateUser.setHeadPhoto(saveHeadPhoto(user.getUserName(),headPhoto));
			}
			UserDao dao = new UserDao();
			//执行更新操作
			if (dao.update(updateUser) > 0) {
				out.println("更新成功！");
				//更新成功后也更新保存在session对象中的User对象
				request.getSession().setAttribute("loginUser", updateUser);
			}else{
				out.println("更新失败！");
			}
			response.setHeader("Refresh", "2;account_details.jsp");
			out.close();
		}
	}
	/**
	 * 将上传的照片保存到自定义目录。在@MultipartConfig(location="d:/")设置的目录必须为绝对路径。
	 * 此方法中的目录可通过相对路径设置。
	 * @param savePhotoDir  保存照片的目录
	 * @param part 上传的Part对象
	 * @throws IOException
	 */
	private String saveHeadPhoto(String userName,Part part) throws IOException{
		String fileName = part.getSubmittedFileName();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		File saveFile = new File(saveRealPath+userName+suffix);
		FileOutputStream fos = new FileOutputStream(saveFile);
		InputStream inputStream = part.getInputStream();
		byte[] buff = new byte[1024];
		int readLen = 0;
		while ((readLen = inputStream.read(buff)) != -1) {
			fos.write(buff, 0, readLen);
		}
		
		inputStream.close();
		fos.close();
		return saveFile.getAbsolutePath();
	}

}
